package com.link.base.base.servicerequest.controller;

import com.link.base.user.model.CoreUser;
import com.link.base.base.user.model.User;
import com.link.base.base.common.model.Attachment;
import com.link.base.base.common.service.AttachmentService;
import com.link.base.base.servicerequest.model.ServiceRequest;
import com.link.base.base.servicerequest.service.ServiceRequestService;
import com.link.base.base.user.service.UserService;
import com.link.core.cllog.LCLogger;
import com.link.core.basic.annotations.JsonParam;
import com.link.core.basic.controller.BasicController;
import com.link.core.basic.interceptor.SecurityInterceptor;
import com.link.core.basic.model.BasicModel;
import com.link.core.basic.query.QueryParams;
import com.link.core.basic.service.BasicService;
import com.link.core.basic.service.KeyGenerateService;
import com.link.core.util.DateUtil;
import com.link.core.util.UserUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * @author unknown
 * @date unknown
 * @comments 服务请求
 */
@Controller
@RequestMapping("/link/service")
public class ServiceRequestController extends BasicController<ServiceRequest> {

    @Resource
    private ServiceRequestService serviceRequestService;
    @Resource
    private KeyGenerateService keyGenerateService;
    @Resource
    private UserService userService;
    @Resource
    private AttachmentService attachmentService;

    @Override
    public BasicService<ServiceRequest> getBasicService() throws Exception {
        return serviceRequestService;
    }

    /**
     * 根据条件查询某段时间的记录
     */
    @RequestMapping(value = "/queryAllServiceRequest")
    @ResponseBody
    public Map<String, Object> queryAllServiceRequest(@JsonParam QueryParams qps, @JsonParam ServiceRequest entity, HttpSession session,
                                                      HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        CoreUser user = UserUtil.getUser();
        try {
            String flag = entity.getCreatedFlag();
            if (flag == "Y" || "Y".equals(flag)) {
                entity.setCreatedBy(user.getId());
            }
            List<ServiceRequest> list = serviceRequestService.queryAllServiceRequest(entity);
            result.put("success", true);
            result.put("rows", list);
            this.pushCurrentDataCache(list, session.getId(), "base", false);
            result.put("total", getCount((BasicModel) entity, list.size()));
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("rows", new ArrayList<ServiceRequest>());
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 根据条件查询某段时间的记录
     */
    @RequestMapping(value = "/queryAllServiceRequestPage")
    @ResponseBody
    public Map<String, Object> queryAllServiceRequestPage(@JsonParam QueryParams qps,@JsonParam  ServiceRequest entity, HttpSession session,
                                                          HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        CoreUser user = UserUtil.getUser();
        try {
            ServiceRequest t = (ServiceRequest) BasicModel.transformClass(entity, qps);
            String flag = entity.getCreatedFlag();
            if (flag == "Y" || "Y".equals(flag)) {
                entity.setCreatedBy(user.getId());
            }
            List<ServiceRequest> list = serviceRequestService.queryAllServiceRequest(t);
            result.put("success", true);
            result.put("rows", list);
            this.pushCurrentDataCache(list, session.getId(), "base", false);
            result.put("total", getCount((BasicModel) entity, list.size()));
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("rows", new ArrayList<ServiceRequest>());
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 根据id查询记录
     */
    @RequestMapping(value = "/queryByServiceRequestId")
    @ResponseBody
    public Map<String, Object> queryByServiceRequestId(@RequestBody ServiceRequest entity, HttpSession session,
                                                       HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            ServiceRequest ob = serviceRequestService.queryByServiceRequestId(entity);

            result.put("success", true);
            result.put("result", ob);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 新建服务请求
     */
    @RequestMapping(value = "/serviceRequestInsert")
    @ResponseBody
    public Map<String, Object> serviceRequestInsert(@RequestBody ServiceRequest entity, HttpSession session,
                                                    HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            entity.setId(keyGenerateService.keyGenerate());
            serviceRequestService.serviceRequestInsert(entity);
            ServiceRequest ob = serviceRequestService.queryByServiceRequestId(entity);
            result.put("success", true);
            result.put("newRow", ob);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 更新服务请求
     */
    @RequestMapping(value = "/serviceRequestUpdate")
    @ResponseBody
    public Map<String, Object> serviceRequestUpdate(@RequestBody ServiceRequest entity, HttpSession session,
                                                    HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            //app领取优惠卷，获取一个默认登录用户
            // 获取一个默认登录用户
            User user = userService.queryUserByCropId(entity.getCorpid());
            SecurityInterceptor.tempUser.set(user);
            entity.setAttachmentList(null);
            serviceRequestService.serviceRequestUpdate(entity);
            ServiceRequest ob = serviceRequestService.queryByServiceRequestId(entity);
            result.put("success", true);
            result.put("result", ob);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 新建服务请求（无状态登录）
     * @author wangdwei
     */
    @RequestMapping(value = "/newServiceReqlogOut")
    @ResponseBody
    public Map<String, Object> newServiceReqlogOut(@JsonParam ServiceRequest entity, HttpSession session,
                                                   HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            // 获取一个默认登录用户
            User user = userService.queryUserByCropId(entity.getCorpid());
            SecurityInterceptor.tempUser.set(user);
            entity.setCreatedBy(user.getId());
            String date = DateUtil.dateToStr(new Date(),"yyyy-MM-dd HH:mm:ss");
            entity.setCreated(date);
            entity.setLastUpdated(date);
            entity.setLastUpdatedBy(0L);
            entity.setCorpid(user.getCorpid());
            serviceRequestService.newRecord(entity);
            ServiceRequest ob = serviceRequestService.queryByServiceRequestId(entity);
            result.put("success", true);
            result.put("newRow", ob);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }


    /**
     * DESC: 匿名用户提交附件操作
     *
     * @param:
     * @return:
     * @auther: bowen.xu
     * @date: 2018-12-25 11:58
     */
    @RequestMapping(value = "/newAttachmentlogOut", method = RequestMethod.POST, produces = "application/json")
    public Map<String, Object> newAttachmentlogOut(@RequestParam("file") MultipartFile multiFile, // 获取的MultipartFile文件，参数为'file',
                                          HttpServletRequest request, HttpServletResponse respone) {

        String headId = request.getParameter("headId");
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            // 获取一个默认登录用户
            User user = new User();
            user.setCorpid(0L);
            user.setId(0L);
            user.setUsername("websiteAnonymous");
            SecurityInterceptor.tempUser.set(user);

            //上传、入附件信息
            Attachment record = new Attachment();
            record.setModuleType("websiteServiceReq");
            record.setSource("website");
            record.setHeadId(Long.parseLong(headId));
            attachmentService.upload(multiFile, record);
            attachmentService.insert(record);
            Attachment attachment = attachmentService.queryById(record);
            map.put("success", "true");
            map.put("attachment", attachment);
        } catch (Exception e) {
            LCLogger.withException(e);
            map.put("result", e.getMessage());
            map.put("success", false);
        }
        return map;
    }


    /**
     * wngdawei
     * 根据条件查询某段时间的记录,当前登陆人id赋值给创建人
     */
    @Override
    public void beforQueryAllOrExample(ServiceRequest entity, HttpServletRequest request) throws Exception {
        CoreUser user = UserUtil.getUser();
        String flag = entity.getCreatedFlag();
        if ("Y".equals(flag)) {
            entity.setCreatedBy(user.getId());
        }
        //反馈特殊数据筛选需求
        entity.setAttr5("queryByTempPage");
    }
}
